import router from '@/router'
import { permissionStore } from '@/store/modules/permission'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import { App, toRaw } from 'vue'
import { userModule } from '@/store/modules/user'
import { ElMessageBox } from 'element-plus'
nprogress.configure({ showSpinner: true })
// 路由登录做校验，校验用户权限
export const permission = (app: App) => {
  router.beforeEach(async(to) => {
    nprogress.start()
    if (!permissionStore.isInited) {
      try {
        if (userModule.token) {
          //
          permissionStore.setInitStatus(true)
          // 初始化菜单
          await permissionStore.generateRoutes()
          // 替换
          const routes = toRaw(permissionStore.routes)
          const otherRoutes = toRaw(permissionStore.otherRoutes)
          ;[...routes, ...otherRoutes].forEach(item => {
            router.addRoute(item)
          })
          // return true
          return to.fullPath
        } else if (to.path !== '/login') {
          ElMessageBox.alert(
            '您当前没有权限访问！',
            '请登录',
            {
              confirmButtonText: '重新登录',
              type: 'warning',
              callback: () => {
                userModule.LogOut()
                goLogin()
              }
            }
          )
        }
      } catch (e) {
        // eslint-disable-next-line no-console
        console.error('数据初始化失败', e)
      }
    }
  })
  router.afterEach((to) => {
    document.title = to.meta.title
    nprogress.done()
  })
  /**
 * 通用跳转
 */
  const goLogin = () => {
    const url = window.location.href
    window.location.href = `${location.origin}/login?redirect=${encodeURIComponent(url)}`
  }
  app.use(router)
}
